package com.mission.schedule.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.R;
import com.mission.schedule.adapter.AddFriendsAdapter;
import com.mission.schedule.adapter.utils.CommonAdapter;
import com.mission.schedule.adapter.utils.ViewHolder;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.AddFriendsBackBean;
import com.mission.schedule.bean.AddFriendsBean;
import com.mission.schedule.bean.MySchBean;
import com.mission.schedule.bean.RepeatBean;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.circleview.CircularImage;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.my160920.widget.EditTextC;
import com.mission.schedule.service.NoteService;
import com.mission.schedule.service.NoteShareService;
import com.mission.schedule.utils.ActivityManager1;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.ListViewForScrollView;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.NetUtil.NetWorkState;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.PullToRefreshView;
import com.mission.schedule.utils.PullToRefreshView.OnFooterRefreshListener;
import com.mission.schedule.utils.PullToRefreshView.OnHeaderRefreshListener;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.Utils;
import com.mission.schedule.widget.SwipeLinearLayout;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class NewFriendsActivity extends BaseActivity implements
        OnClickListener, OnFooterRefreshListener, OnHeaderRefreshListener {

    @ViewResId(id = R.id.top_ll_left)
    private LinearLayout top_ll_left;
    @ViewResId(id = R.id.myfriend_pull_refresh_view)
    private PullToRefreshView mPullToRefreshView;
    @ViewResId(id = R.id.sousuojieguo_tv)
    private TextView sousuojieguo_tv;
    @ViewResId(id = R.id.nosousuojieguo_tv)
    private TextView nosousuojieguo_tv;
    @ViewResId(id = R.id.addfriends_lv)
    private ListViewForScrollView addfriends_lv;
    @ViewResId(id = R.id.sousuocontent_et)
    private EditTextC sousuocontent_et;
    @ViewResId(id = R.id.sousuo_iv)
    private ImageView sousuo_iv;
    @ViewResId(id = R.id.view)
    private View view;
    @ViewResId(id = R.id.myschedule_title)
    private TextView myschedule_title;

    Context context;
    private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部
    private boolean mRefreshFlag = false;// 判断是否刷新
    private boolean isDel = true;
    AddFriendsAdapter addFriendsAdapter;
    AddFriendsAdapter1 addFriendsAdapter1;
    List<AddFriendsBean> addFriendsList;

    String path;
    String SouSuoPath;

    SharedPrefUtil prefUtil = null;
    String userId;
    String type, titleid = "", title = "", titleimg = "",noteusername = "",title_userid="";
    int position;
    ActivityManager1 activityManager = null;

    private String cpidhandler = "";
    List<newFriendBean.PageBean.ItemsBean> itemsBeanList = new ArrayList<>();

    int zhuanfatype = 0;//0 清单 1 重复
    int type1 = -1;
    int schSourceType = 0;
    RepeatBean repeatBean;
    SharedPrefUtil sharedPrefUtil;
    MySchBean mySchBean = null;
    @Override
    protected void setListener() {
        top_ll_left.setOnClickListener(this);
        sousuo_iv.setOnClickListener(this);
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_newfriend);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        context = this;
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        prefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        userId = prefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "");
        activityManager = ActivityManager1.getInstance();
        activityManager.addActivities(this);
        zhuanfatype = getIntent().getIntExtra("type", 0);
        titleid = getIntent().getStringExtra("titleid");
        title = getIntent().getStringExtra("title");
        titleimg = getIntent().getStringExtra("titleimg");
        noteusername = getIntent().getStringExtra("noteusername");
        title_userid = getIntent().getStringExtra("title_userid");
        if (zhuanfatype == 4) {
            mySchBean = (MySchBean) getIntent().getSerializableExtra("bean");
        } else if(zhuanfatype == 2){
            schSourceType = getIntent().getIntExtra("schSourceType",0);
            type1 = getIntent().getIntExtra("type1",-1);
        }else {
            if (title.equals("搜索")) {
                zhuanfatype = -1;
                myschedule_title.setText(title);
                sousuocontent_et.setText(getIntent().getStringExtra("content"));
                initdata();
            } else {
                repeatBean = (RepeatBean) getIntent().getSerializableExtra("bean");
            }
        }


        view.setVisibility(View.GONE);
        sousuojieguo_tv.setVisibility(View.VISIBLE);
        sousuojieguo_tv.setTextColor(Color.parseColor("#00000000"));
        sousuocontent_et.setEdittextCoutomListener(new EditTextC.EdittextCoutomListener() {
            @Override
            public void enter(int index, String text) {
                initdata();
            }

            @Override
            public void delete(int index, String text) {

            }

            @Override
            public void textchange(int index, boolean hastext) {

            }
        });


        if (title != "搜索" && zhuanfatype != -1) {
            itemsBeanList = App.getDBcApplication().getAllNewFriendData(userId, false);
            addFriendsAdapter1 = new AddFriendsAdapter1(context, itemsBeanList, R.layout.adapter_addfriends, handler);
            addfriends_lv.setAdapter(addFriendsAdapter1);
        }

    }

    @Override
    protected void setAdapter() {

    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            position = msg.arg1;
            switch (msg.what) {
                case 3:
                    int position = msg.arg1;
                    newFriendBean.PageBean.ItemsBean itemsBea = (newFriendBean.PageBean.ItemsBean) msg.obj;
                    if (App.getDBcApplication().getNewFriendUpdateState(itemsBea.id) == 1){
                        App.getDBcApplication().deleteNewFriendData(itemsBea.id,userId,true);
                    }else {
                        App.getDBcApplication().deleteNewFriendData(itemsBea.id,userId,false);
                    }
                    itemsBeanList.remove(position);
                    addFriendsAdapter1.notifyDataSetChanged();
                    break;
                case 0:
                    AddFriendsBean friendsbean = (AddFriendsBean) msg.obj;
                    if (zhuanfatype == -1) {
                        AddDailog(friendsbean);
                    } else {
                        boolean isSave = false;
                        List<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> listBeanList = App.getDBcApplication().getAllNewFriendData(userId, false);
                        for (NewFriendsActivity.newFriendBean.PageBean.ItemsBean itemsBean : listBeanList) {
                            if (itemsBean.pname.equals(friendsbean.uname)) {
                                isSave = true;
                                break;
                            }
                        }
                        if (!isSave) {
                            newFriendBean.PageBean.ItemsBean itemsBean = new newFriendBean.PageBean.ItemsBean();
                            itemsBean.pname = friendsbean.uname;
                            itemsBean.uid = Integer.valueOf(userId);
                            itemsBean.puid = friendsbean.uid;
                            itemsBean.pimgs = friendsbean.titleImg;
                            itemsBean.id = App.getDBcApplication().getNFMinId() - 1;
                            itemsBean.createTime = DateUtil.nowTime();
                            itemsBean.changeTime = DateUtil.nowTime();
                            itemsBean.remark = "";
                            itemsBean.remark1 = "";
                            itemsBean.type = 0;
                            App.getDBcApplication().saveNewFriendData(itemsBean, 1);
                        }
                        if (zhuanfatype == 2) {
                            checkIsTB(friendsbean.uid + "", title_userid, title, titleid, titleimg,
                                    noteusername, sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""), friendsbean.uname);
                        } else if (zhuanfatype == 4) {
                            postPersonCalerder(friendsbean.uid + "", friendsbean.titleImg, friendsbean.uname);
                        } else {
                            if (titleid.equals("00")) {
                                Intent intent = new Intent(context, NoteOtherListActivity.class);
                                intent.putExtra("name", friendsbean.uname);
                                intent.putExtra("puid", friendsbean.uid + "");
                                startActivity(intent);
                            } else {
                                if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
                                    if (zhuanfatype == 0) {
                                        Intent intentnewf = new Intent(context, NoteShareService.class);
                                        intentnewf.setAction("noteshare");
                                        intentnewf.putExtra("maxTitleId", titleid);
                                        intentnewf.putExtra("title", title);
                                        intentnewf.putExtra("uid", friendsbean.uid);
                                        intentnewf.setPackage(context.getPackageName());
                                        context.startService(intentnewf);
                                    } else {
                                        sendRepeat(friendsbean.uid);
                                    }
                                    Toast.makeText(context, "已发送！", Toast.LENGTH_SHORT).show();
                                    finish();
                                } else {
                                    Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                    break;
                case 2:
                    newFriendBean.PageBean.ItemsBean itemsBean1 = (newFriendBean.PageBean.ItemsBean) msg.obj;
                    if (zhuanfatype == 2) {
                        checkIsTB(itemsBean1.puid+"", title_userid, title, titleid, titleimg, noteusername,sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""),itemsBean1.pname);
                    } else if(zhuanfatype == 4) {
                        postPersonCalerder(itemsBean1.puid+"",itemsBean1.pimgs,itemsBean1.pname);
                    } else {
                        if (titleid.equals("00")) {
                            Intent intent = new Intent(context, NoteOtherListActivity.class);
                            intent.putExtra("name", itemsBean1.pname);
                            intent.putExtra("puid", itemsBean1.puid + "");
                            startActivity(intent);
                        } else {
                            if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
                                if (zhuanfatype == 0) {
                                    Intent intentnewf = new Intent(context, NoteShareService.class);
                                    intentnewf.setAction("noteshare");
                                    intentnewf.putExtra("maxTitleId", titleid);
                                    intentnewf.putExtra("title", title);
                                    intentnewf.putExtra("uid", itemsBean1.puid);
                                    intentnewf.setPackage(context.getPackageName());
                                    context.startService(intentnewf);
                                } else {
                                    sendRepeat(itemsBean1.puid);
                                }
                                Toast.makeText(context, "已发送！", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;

            }
        }

    };

    private void initdata() {
        if (Utils.checkMobilePhone(sousuocontent_et.getText().toString())) {
            type = "1";
        } else if (Utils.isEmail(sousuocontent_et.getText().toString())) {
            type = "2";
        } else {
            type = "0";
        }
        String uname = sousuocontent_et.getText().toString().trim();
        sousuocontent_et.setSelection(uname.length());
        SouSuoPath = URLConstants.搜索添加好友;
        Map<String, String> pairs = new HashMap<String, String>();
        pairs.put("uId", userId);
        pairs.put("uName", uname);
        pairs.put("nowPage", "1");
        pairs.put("pageNum", "40");
        pairs.put("type", type);
        if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
            SouSuoAsync(SouSuoPath, pairs);
        } else {
            Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_ll_left:
                Intent intent = new Intent();
                intent.putExtra("cpidhandler", cpidhandler);
                setResult(Activity.RESULT_OK, intent);
                this.finish();
                break;
            case R.id.sousuo_iv:
                initdata();
                break;
            default:
                break;
        }
    }

    int i = 1;

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
//        mPullToRefreshView.onHeaderRefreshComplete();
        UpdateLoadAsyncNewFriend();
    }


    private void UpdateLoadAsyncNewFriend() {
        StringRequest request = new StringRequest(Method.POST, URLConstants.查询常用联系人刷新信息,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String result) {

                        if (!TextUtils.isEmpty(result)) {
                            Gson gson = new Gson();
                            UpdateUserBean updateUserBean = gson.fromJson(result, UpdateUserBean.class);
                            if (updateUserBean.status == 0){
                                List<UpdateUserBean.ListBean> list = updateUserBean.list;
                                if (list != null){
                                    for (UpdateUserBean.ListBean bean : list){
                                        App.getDBcApplication().updateNewFriendData(bean.uId,bean.uPortrait,bean.uNickName);
                                    }
                                }
                                itemsBeanList = App.getDBcApplication().getAllNewFriendData(userId, false);
                                addFriendsAdapter1 = new AddFriendsAdapter1(context, itemsBeanList, R.layout.adapter_addfriends, handler);
                                addfriends_lv.setAdapter(addFriendsAdapter1);
                            }
                        }

                        mPullToRefreshView.onHeaderRefreshComplete();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mPullToRefreshView.onHeaderRefreshComplete();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("uId", userId);
                return map;
            }
        };
        request.setTag("updateuser");
        request.setRetryPolicy(new DefaultRetryPolicy(2000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    boolean iscom = false;

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        if (iscom) {
            mPullToRefreshView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mRefreshHeadFlag = false;
                    mRefreshFlag = true;
                    ++i;
                    Map<String, String> pairs = new HashMap<String, String>();
                    pairs.put("uId", userId);
                    pairs.put("uName", sousuocontent_et.getText().toString().trim());
                    pairs.put("nowPage", i + "");
                    pairs.put("pageNum", "40");
                    pairs.put("type", type);
                    String URLpath = URLConstants.搜索添加好友;
                    SouSuoAsync(URLpath, pairs);
                }
            }, 100);
        } else {
            mPullToRefreshView.onFooterRefreshComplete();
        }

    }

    private void SouSuoAsync(String path, final Map<String, String> map) {
        final ProgressUtil progressUtil = new ProgressUtil();
        if (!mRefreshFlag) {
            progressUtil.ShowProgress(context, true, true, "正在努力加载......");
        }
        StringRequest request = new StringRequest(Method.POST, path,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String result) {
                        if (mRefreshFlag) {
                            mPullToRefreshView.onHeaderRefreshComplete();
                            mPullToRefreshView.onFooterRefreshComplete();
                        } else {
                            progressUtil.dismiss();
                        }
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                if (mRefreshHeadFlag) {
                                    addFriendsAdapter = null;
                                }
                                Gson gson = new Gson();
                                AddFriendsBackBean backBean = gson.fromJson(
                                        result, AddFriendsBackBean.class);
                                if (backBean.status == 0) {
                                    iscom = true;
                                    if (addFriendsAdapter == null) {
                                        addFriendsList = backBean.list;
                                        if (addFriendsList != null
                                                && addFriendsList.size() > 0) {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv.setTextColor(context.getResources().getColor(R.color.gongkai_txt));
                                            view.setVisibility(View.VISIBLE);
                                        } else {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            view.setVisibility(View.GONE);
                                        }
                                        addFriendsAdapter = new AddFriendsAdapter(
                                                context, addFriendsList,
                                                R.layout.adapter_addfriends,
                                                handler);
                                        addfriends_lv
                                                .setAdapter(addFriendsAdapter);
                                    } else {
                                        addFriendsList.addAll(backBean.list);
                                        if (addFriendsList != null
                                                && addFriendsList.size() > 0) {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv.setTextColor(context.getResources().getColor(R.color.gongkai_txt));
                                            view.setVisibility(View.VISIBLE);
                                        } else {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            view.setVisibility(View.GONE);
                                        }
                                        addFriendsAdapter.notifyDataSetChanged();
                                    }
                                } else {
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            if (isDel) {
                                addFriendsList = new ArrayList<AddFriendsBean>();
                                addFriendsAdapter = new AddFriendsAdapter(
                                        context, addFriendsList,
                                        R.layout.adapter_addfriends, handler);
                                addfriends_lv.setAdapter(addFriendsAdapter);
                            }
                            return;
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isDel = false;
                progressUtil.dismiss();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }
        };
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }


    public static class newFriendBean {

        /**
         * message : 成功
         * status : 0
         * page : {"totalPage":3,"currentPage":0,"items":[{"puid":1140656,"remark":"","uid":52432,"id":7,"remark1":null,"pname":"布丁奶茶","pimgs":"20161101/630959.png","changeTime":"2017-05-08T10:35:49","type":0,"createTime":"2017-05-08T10:35:49"},{"puid":260975,"remark":"加油加油！积极","uid":52432,"id":5,"remark1":null,"pname":"清流暖人心","pimgs":"20161120/234789.png","changeTime":"2017-05-04T11:59:10","type":0,"createTime":"2017-05-04T11:59:10"}],"pageSize":40,"totalCount":2}
         */

        public String message;
        public int status;
        public PageBean page;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public PageBean getPage() {
            return page;
        }

        public void setPage(PageBean page) {
            this.page = page;
        }

        public static class PageBean {
            /**
             * totalPage : 3
             * currentPage : 0
             * items : [{"puid":1140656,"remark":"","uid":52432,"id":7,"remark1":null,"pname":"布丁奶茶","pimgs":"20161101/630959.png","changeTime":"2017-05-08T10:35:49","type":0,"createTime":"2017-05-08T10:35:49"},{"puid":260975,"remark":"加油加油！积极","uid":52432,"id":5,"remark1":null,"pname":"清流暖人心","pimgs":"20161120/234789.png","changeTime":"2017-05-04T11:59:10","type":0,"createTime":"2017-05-04T11:59:10"}]
             * pageSize : 40
             * totalCount : 2
             */

            public int totalPage;
            public int currentPage;
            public int pageSize;
            public int totalCount;
            public List<ItemsBean> items;

            public int getTotalPage() {
                return totalPage;
            }

            public void setTotalPage(int totalPage) {
                this.totalPage = totalPage;
            }

            public int getCurrentPage() {
                return currentPage;
            }

            public void setCurrentPage(int currentPage) {
                this.currentPage = currentPage;
            }

            public int getPageSize() {
                return pageSize;
            }

            public void setPageSize(int pageSize) {
                this.pageSize = pageSize;
            }

            public int getTotalCount() {
                return totalCount;
            }

            public void setTotalCount(int totalCount) {
                this.totalCount = totalCount;
            }

            public List<ItemsBean> getItems() {
                return items;
            }

            public void setItems(List<ItemsBean> items) {
                this.items = items;
            }

            public static class ItemsBean {
                /**
                 * puid : 1140656
                 * remark :
                 * uid : 52432
                 * id : 7
                 * remark1 : null
                 * pname : 布丁奶茶
                 * pimgs : 20161101/630959.png
                 * changeTime : 2017-05-08T10:35:49
                 * type : 0
                 * createTime : 2017-05-08T10:35:49
                 */

                public int puid;
                public String remark;
                public int uid;
                public int id;
                public String remark1;
                public String pname;
                public String pimgs;
                public String changeTime;
                public int type;
                public String createTime;

                public int getPuid() {
                    return puid;
                }

                public void setPuid(int puid) {
                    this.puid = puid;
                }

                public String getRemark() {
                    return remark;
                }

                public void setRemark(String remark) {
                    this.remark = remark;
                }

                public int getUid() {
                    return uid;
                }

                public void setUid(int uid) {
                    this.uid = uid;
                }

                public int getId() {
                    return id;
                }

                public void setId(int id) {
                    this.id = id;
                }

                public String getRemark1() {
                    return remark1;
                }

                public void setRemark1(String remark1) {
                    this.remark1 = remark1;
                }

                public String getPname() {
                    return pname;
                }

                public void setPname(String pname) {
                    this.pname = pname;
                }

                public String getPimgs() {
                    return pimgs;
                }

                public void setPimgs(String pimgs) {
                    this.pimgs = pimgs;
                }

                public String getChangeTime() {
                    return changeTime;
                }

                public void setChangeTime(String changeTime) {
                    this.changeTime = changeTime;
                }

                public int getType() {
                    return type;
                }

                public void setType(int type) {
                    this.type = type;
                }

                public String getCreateTime() {
                    return createTime;
                }

                public void setCreateTime(String createTime) {
                    this.createTime = createTime;
                }
            }
        }
    }


    public class AddFriendsAdapter1 extends CommonAdapter<newFriendBean.PageBean.ItemsBean> {

        Context context;
        private Handler handler;
        private DisplayImageOptions options; // DisplayImageOptions是用于设置图片显示的类
        private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
        private ImageLoader imageLoader;
        List<SwipeLinearLayout> swipeLinearLayouts = new ArrayList<>();
        public AddFriendsAdapter1(Context context, List<newFriendBean.PageBean.ItemsBean> lDatas,
                                  int layoutItemID, Handler handler) {
            super(context, lDatas, layoutItemID);
            this.context = context;
            this.handler = handler;
            // 使用DisplayImageOptions.Builder()创建DisplayImageOptions
            options = new DisplayImageOptions.Builder()
                    .showStubImage(R.mipmap.img_null_smal) // 设置图片下载期间显示的图片
                    .showImageForEmptyUri(R.mipmap.img_null_smal) // 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.mipmap.img_null_smal) // 设置图片加载或解码过程中发生错误显示的图片
                    .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                    .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                    // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                    .build(); // 创建配置过得DisplayImageOption对象
            imageLoader = ImageLoader.getInstance();
        }

        private void setOnclick(int positions, newFriendBean.PageBean.ItemsBean bean, int what) {

            Message message = Message.obtain();
            message.arg1 = positions;
            message.obj = bean;
            message.what = what;
            handler.sendMessage(message);
        }

        @Override
        public void getViewItem(ViewHolder holder, final newFriendBean.PageBean.ItemsBean friendsBean, final int position) {
            CircularImage friend_img = holder.getView(R.id.friend_img);
            LinearLayout person_ll = holder.getView(R.id.person_ll);
            TextView friendname_tv = holder.getView(R.id.friendname_tv);
            TextView friendtag_tv = holder.getView(R.id.friendtag_tv);
            final SwipeLinearLayout swipeLayout = holder.getView(R.id.swipeLayout);
            TextView tv_delete = holder.getView(R.id.tv_delete);
            swipeLinearLayouts.add(swipeLayout);
            swipeLayout.setOnSwipeListener(new SwipeLinearLayout.OnSwipeListener() {
                @Override
                public void onDirectionJudged(SwipeLinearLayout thisSll, boolean isHorizontal) {
                    if (false == isHorizontal) {
                        for (SwipeLinearLayout sll : swipeLinearLayouts) {
                            if (null == sll) {
                                continue;
                            }
                            sll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                        }
                    } else {
                        for (SwipeLinearLayout sll : swipeLinearLayouts) {
                            if (null == sll) {
                                continue;
                            }
                            if (!sll.equals(thisSll)) {
                                //划开一个sll， 其他收缩
                                sll.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                            }
                        }
                    }
                }
            });
            tv_delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    setOnclick(position, friendsBean ,3);
                    swipeLayout.scrollAuto(SwipeLinearLayout.DIRECTION_SHRINK);
                }
            });

            if (friendsBean.pname == null) {
                friendname_tv.setText("@无名称");
            } else {
                friendname_tv.setText("@" + friendsBean.pname);
            }
            friendtag_tv.setText("暂无消息!");
            String imageUrl = "";
            if (!"".equals(friendsBean.pimgs)) {
                imageUrl = friendsBean.pimgs.toString();
            }
            String imageurl = URLConstants.图片 + imageUrl + "&imageType=2&imageSizeType=3";
            imageLoader.displayImage(imageurl, friend_img, options,
                    animateFirstListener);

            friend_img.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    setOnclick(position, friendsBean, 2);
                }
            });
            person_ll.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    setOnclick(position, friendsBean, 2);
                }
            });
        }

        /**
         * 图片加载第一次显示监听器
         *
         * @author Administrator
         */
        private class AnimateFirstDisplayListener extends
                SimpleImageLoadingListener {

            final List<String> displayedImages = Collections
                    .synchronizedList(new LinkedList<String>());

            @Override
            public void onLoadingComplete(String imageUri, View view,
                                          Bitmap loadedImage) {
                if (loadedImage != null) {
                    ImageView imageView = (ImageView) view;
                    // 是否第一次显示
                    boolean firstDisplay = !displayedImages.contains(imageUri);
                    if (firstDisplay) {
                        // 图片淡入效果
                        FadeInBitmapDisplayer.animate(imageView, 500);
                        displayedImages.add(imageUri);
                    }
                }
            }
        }
    }


    private void sendRepeat(int postid) {
        if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
            try {
                JSONObject jsonobject1 = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                JSONObject jsonobject = new JSONObject();
                jsonobject.put("repID", repeatBean.repID);
                jsonobject.put("repUid", postid);
                jsonobject.put("repBeforeTime", repeatBean.repBeforeTime);
                jsonobject.put("repColorType", repeatBean.repColorType);
                jsonobject.put("repDisplayTime", repeatBean.repDisplayTime);
                jsonobject.put("repType", repeatBean.repType);
                jsonobject.put("repIsAlarm", repeatBean.repIsAlarm);
                jsonobject.put("repIsPuase", repeatBean.repIsPuase);
                jsonobject.put("repIsImportant", repeatBean.repIsImportant);
                jsonobject.put("repSourceType", repeatBean.repSourceType);
                jsonobject.put("repLastCreatedTime", repeatBean.repLastCreatedTime);
                jsonobject.put("repInitialCreatedTime", repeatBean.repInitialCreatedTime);
                jsonobject.put("repNextCreatedTime", repeatBean.repNextCreatedTime);
                jsonobject.put("repTypeParameter", repeatBean.repTypeParameter);
                jsonobject.put("repStartDate", repeatBean.repStartDate);
                jsonobject.put("repContent", repeatBean.repContent + "("+sharedPrefUtil.getString(getApplicationContext(),
                        ShareFile.USERFILE, ShareFile.USERNAME, "")+")");
                jsonobject.put("repCreateTime", repeatBean.repCreateTime);
                jsonobject.put("repSourceDesc", repeatBean.repSourceDesc);
                jsonobject.put("repSourceDescSpare", repeatBean.repSourceDescSpare);
                jsonobject.put("repTime", repeatBean.repTime);
                jsonobject.put("repRingDesc", repeatBean.repRingDesc);
                jsonobject.put("repRingCode", repeatBean.repRingCode);
                jsonobject.put("repUpdateTime", repeatBean.repUpdateTime);
                jsonobject.put("repOpenState", repeatBean.repOpenState);
                jsonobject.put("recommendedUserName", sharedPrefUtil.getString(getApplicationContext(),
                        ShareFile.USERFILE, ShareFile.USERNAME, ""));
                jsonobject.put("recommendedUserId", Integer.valueOf(userId));
                jsonobject.put("repDateOne", repeatBean.repDateOne);
                jsonobject.put("repDateTwo", repeatBean.repDateTwo);
                jsonobject.put("repStateOne", repeatBean.repStateOne);
                jsonobject.put("repStateTwo", repeatBean.repStateTwo);
                jsonobject.put("repAType", repeatBean.aType);
                jsonobject.put("repWebURL", repeatBean.webUrl);
                jsonobject.put("repImagePath", repeatBean.imgPath);
                jsonobject.put("repInSTable", repeatBean.repInSTable);
                jsonobject.put("repEndState", 1);
                jsonobject.put("parReamrk", repeatBean.parReamrk);
                jsonobject.put("repRead", 1);
                jsonArray.put(jsonobject);

                jsonobject1.put("tbTtimepreinstall", jsonArray);
                String content;
                String strdate = repeatBean.repTypeParameter
                        .replace("[", "").replace("]", "").replace("\n\"", "").replace("\n", "")
                        .replace("\"", "").toString();
                String weekStr;
                if ("1".equals(repeatBean.repType)) {
                    content = "每天 " + repeatBean.repTime + " "+repeatBean.repContent;
                } else if ("2".equals(repeatBean.repType)) {
                    if (strdate.equals("1")) {
                        weekStr = "一";
                    } else if (strdate.equals("2")) {
                        weekStr = "二";
                    } else if (strdate.equals("3")) {
                        weekStr = "三";
                    } else if (strdate.equals("4")) {
                        weekStr = "四";
                    } else if (strdate.equals("5")) {
                        weekStr = "五";
                    } else if (strdate.equals("6")) {
                        weekStr = "六";
                    } else {
                        weekStr = "日";
                    }
                    content = "周" + weekStr + " " + repeatBean.repTime + " "+repeatBean.repContent;
                } else if ("3".equals(repeatBean.repType)) {
                    content = "每月" + strdate + "日 " + repeatBean.repTime + " "+repeatBean.repContent;
                } else if ("4".equals(repeatBean.repType)) {
                    content = "每年 " + strdate + " "+repeatBean.repTime + " "+repeatBean.repContent;
                } else if("6".equals(repeatBean.repType)){
                    content = "每年 "+ strdate +" "+ repeatBean.repTime + " "+repeatBean.repContent;
                }else {
                    content = "工作日 " + repeatBean.repTime + " "+repeatBean.repContent;
                }
                UpdateLoadAsync(jsonobject1.toString(),content);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(NewFriendsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
        }
    }

    private void UpdateLoadAsync(final String json,final String content) {
        StringRequest request = new StringRequest(Method.POST, URLConstants.重复转发,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String result) {

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(NewFriendsActivity.this, "重复转发失败", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("data", json);
                map.put("type", "1");
                map.put("row1","▶︎ @"+sharedPrefUtil.getString(getApplicationContext(), ShareFile.USERFILE, ShareFile.USERNAME, "")+" 给你转发了一个重复日程");
                map.put("row2","重复 ("+content+")");
                return map;
            }
        };
        request.setTag("sendRepeat");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    final ProgressUtil progressUtil = new ProgressUtil();

    private void checkIsTB(String tuId,String title_userid, String title, String titleid, String titleImg,String noteusername, String name,String pname) {
        if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
            progressUtil.ShowProgress(context, true, true, "发送清单...");
            if (App.getDBcApplication().getNoteTitleState(titleid, userId) != 0) {

                if (App.getDBcApplication().getNoteTitleState(titleid, userId) == -1) {
                    App.getDBcApplication().updateNoteTitleState(titleid, userId, 1, false);
                    App.getDBcApplication().updateNoteTitleDetailState(titleid, userId, 1);
                }

                uploadlist(tuId,title_userid, title, titleid, titleImg, name,noteusername,pname);

            } else {
                sendNoteOtherCanlender(tuId, title_userid,title, titleid, titleImg,noteusername, name,pname);
            }
        } else {
            Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendNoteOtherCanlender(final String tuId, final String title_userid, final String title,
                                        final String titleid, String titleImg,
                                        final String noteusername , final String name,final String pname) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("uid", tuId);
            jsonObject.put("content", title);
            jsonObject.put("tuId", title_userid);
            jsonObject.put("titleId", titleid);
            jsonObject.put("titleImg", titleImg);
            jsonObject.put("name", noteusername);
            jsonObject.put("remark", title_userid.equals(tuId) ? "" : "来自:"+name);//(@"+name+")
            jsonArray.put(jsonObject);
            jsonObject1.put("ly", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final String datajson = jsonObject1.toString();

        StringRequest request1 = new StringRequest(Method.POST, URLConstants.清单留言公开方发送连接url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (!TextUtils.isEmpty(s)) {
                    try {
                        Gson gson = new Gson();
                        SendBena sendBena = gson.fromJson(s, SendBena.class);
                        if (sendBena.status == 0) {
                            finish();
                            Toast.makeText(context, "发送成功", Toast.LENGTH_SHORT).show();
                            ly(pname);
                        } else {
                            Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                        Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
                }
                progressUtil.dismiss();
            }


        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                progressUtil.dismiss();
                Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("data", datajson);
                map.put("row1","▶︎ @"+sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, "")+" 给你转发一个清单链接");
                if (type1 == 0){
                    map.put("row2",noteusername+": #"+ title+"#");
                }else {
                    map.put("row2","#"+ title+"#");
                }
                return map;
            }
        };
        request1.setTag("sendNoteOtherCanlender");
        request1.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request1);


        StringRequest request = new StringRequest(Method.POST, URLConstants.清单留言加入清单到日程时候调用, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
            }


        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("titleId", titleid);
                map.put("uId", tuId+"");
                map.put("cuId", userId);
                return map;
            }
        };
        request.setTag("sendsc");
        request.setRetryPolicy(new DefaultRetryPolicy(5000, 1, 1.0f));
        App.getHttpQueues().add(request);

    }

    /**
     * 系统留言
     */
    private void ly(String name){
        String data = lyJsonStrinf("将清单转发给了@"+name);
        HttpUtils httpUtils = new HttpUtils(2000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("row1","▶︎ @"+sharedPrefUtil.getString(getApplicationContext(), ShareFile.USERFILE, ShareFile.USERNAME, "")+" 将清单转发给了@"+name);
        params.addBodyParameter("row2","#"+title+"#");
        params.addBodyParameter("data", data);
        httpUtils.send(HttpMethod.POST, URLConstants.清单留言同步主留言信息, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }

    private String lyJsonStrinf(String mess){
        JSONObject ly = new JSONObject();
        try {
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", -1);
            jsonObject.put("mess", mess);
            jsonObject.put("updateState", 1);
            jsonObject.put("uid", userId);
            jsonObject.put("lyUid", userId);
            jsonObject.put("lyName", sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""));
            jsonObject.put("titleId", titleid);
            jsonObject.put("cId", 0);
            jsonObject.put("localTimes", DateUtil.formatDateTimeSs(new Date()));
            jsonObject.put("type", 1);//0 普通留言 1 系统留言
            jsonObject.put("reamrk1", android.os.Build.MODEL.replace(" ","")+" "+android.os.Build.VERSION.RELEASE);
            jsonObject.put("lyTitleImg", sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, ""));
            jsonObject.put("reamrk", title);
            jsonObject.put("changeTime",DateUtil.formatDateTimeSs(new Date()));
            jsonArray.put(jsonObject);
            ly.put("ly",jsonArray);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ly.toString();
    }

    /**
     * 上传图片上传清单数据
     */
    public void uploadlist(String tuId,final String title_userid, String title, String titleid, String titleImg, String name,String noteusername,final String pname) {
        NoteTitleDetailBean.TDelListBean bean = App.getDBcApplication().getOneNoteTitlesData(userId, titleid,false);
        JSONObject tDelListBeanListjsonObject = new JSONObject();
        try {
            JSONArray tDelListBeanListjsonArray = new JSONArray();
            JSONObject js = new JSONObject();
            js.put("id", bean.id);
            js.put("titleId", bean.titleId);
            js.put("uid", bean.uid);
            js.put("titles", bean.titles);
            js.put("imgPath", bean.imgPath);
            js.put("imgUrl", bean.imgUrl);
            js.put("shareUrl", bean.shareUrl);
            js.put("filed", bean.filed);
            js.put("nums", bean.nums);
            js.put("copys", bean.copys);
            js.put("styles", bean.styles);
            js.put("ltype", bean.ltype);
            js.put("orderId", bean.orderId);
            js.put("createTime", bean.createTime);
            js.put("changeTime", bean.changeTime);
            js.put("localTimes", bean.localTimes);
            js.put("remark", bean.remark);
            js.put("remark1", bean.remark1);
            js.put("remark2", bean.remark2);
            js.put("remark3", bean.remark3);
            js.put("puid", bean.puid);
            js.put("pname", bean.pname);
            js.put("states", bean.states);
            js.put("sends", bean.sends);
            js.put("openState", bean.openState);
            js.put("updateState", bean.id < 0 ? 1 : App.getDBcApplication().getNoteTitleState(bean.titleId, userId));
            tDelListBeanListjsonArray.put(js);


            tDelListBeanListjsonObject.put("classTitle", tDelListBeanListjsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //详情
        List<NoteTitleDetailBean.ListBean> listBeanList = App.getDBcApplication().getTitleNoteDetailData(userId, titleid, true);
        JSONObject listjsonObject = new JSONObject();
        try {
            JSONArray listjsonArray = new JSONArray();
            for (NoteTitleDetailBean.ListBean bean1 : listBeanList) {
                JSONObject js = new JSONObject();
                js.put("id", bean1.id);
                js.put("titleId", bean1.titleId);
                js.put("uid", bean1.uid);
                js.put("titles", bean1.titles);
                js.put("imgPath", bean1.imgPath);
                js.put("imgUrl", bean1.imgUrl);
                js.put("shareUrl", bean1.shareUrl);
                js.put("contents", bean1.contents);
                js.put("nums", bean1.nums);
                js.put("style", bean1.style);
                js.put("endstate", bean1.endstate);
                js.put("lType", bean1.lType);
                js.put("orderId", bean1.orderId);
                js.put("createTime", bean1.createTime);
                js.put("changeTime", bean1.changetime);
                js.put("cpath", bean1.cpath);
                js.put("curl", bean1.curl);
                js.put("remark", bean1.remark);
                js.put("remark1", bean1.remark1);
                js.put("remark2", bean1.remark2);
                js.put("remark3", bean1.remark3);
                js.put("remark4", bean1.remark4);
                js.put("updateState", bean1.id < 0 ? 1 : App.getDBcApplication().getNoteTitleDetailState(bean1.titleId, userId, bean1.id));
                listjsonArray.put(js);
            }
            if (listBeanList.size() > 0) {
                listjsonObject.put("class1", listjsonArray);
            } else {
                listjsonObject = null;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        uploadListData(listjsonObject == null ? "" : listjsonObject.toString(),
                tDelListBeanListjsonObject == null ? "" : tDelListBeanListjsonObject.toString()
                , tuId,title_userid, title, titleid, titleImg, name,pname);

    }

    /**
     * 上传清单数据
     *
     * @param
     */
    private void uploadListData(String data, String dataTitle, final String tuId,final String title_userid, final String title,
                                final String titleid, final String titleImg, final String name,final String pname) {
        if (NetUtil.getConnectState(this) == NetWorkState.NONE) {
            Toast.makeText(context, "网络异常，请检查网络！", Toast.LENGTH_SHORT).show();
        } else {
            HttpUtils httpUtils = new HttpUtils(10000);
            final RequestParams params = new RequestParams();
            params.addBodyParameter("data", data);
            params.addBodyParameter("dataTitle", dataTitle);
            httpUtils.send(HttpMethod.POST, URLConstants.清单和清单标题上行, params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException e, String msg) {
                            progressUtil.dismiss();
                            Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
                        }


                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            if (!TextUtils.isEmpty(responseInfo.result)) {
                                Gson gson = new Gson();
                                NoteService.noteSynBean bean = gson.fromJson(responseInfo.result, NoteService.noteSynBean.class);
                                if (bean.status == 0) {
                                    List<NoteService.noteSynBean.TDelListBean> tDeListBeanList = bean.tDelList;

                                    //标题同步没有异常
                                    List<Integer> errorList = new ArrayList<Integer>();

                                    for (NoteService.noteSynBean.TDelListBean tDeListBean : tDeListBeanList) {
                                        if (tDeListBean.dataState == 1) {//新增
                                            if (tDeListBean.state == 0) {//成功
                                                //修改id和状态值
                                                App.getDBcApplication().updateNoteTitleId(tDeListBean.id, tDeListBean.calendId, userId);
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.calendId + "", userId, 0, true);
                                            } else if (tDeListBean.state == 1) {//失败  可以不操作,但是避免意外
                                                //更改状态为1
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userId, 1, true);
                                            } else if (tDeListBean.state == 2) { //异常
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userId, -1, true);
                                                errorList.add(tDeListBean.id);
                                            }
                                        } else if (tDeListBean.dataState == 2) {//修改
                                            if (tDeListBean.state == 0) {//成功
                                                //修改该id状态值
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userId, 0, true);
                                            } else if (tDeListBean.state == 1) {//失败
                                                //更改状态为2
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userId, 2, true);
                                            } else if (tDeListBean.state == 2) { //异常
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userId, -1, true);
                                                errorList.add(tDeListBean.id);
                                            }
                                        } else if (tDeListBean.dataState == 3) {//删除
                                            if (tDeListBean.state == 0) {//成功
                                                //删除该id的清单
                                                App.getDBcApplication().deleteNoteTitleData(tDeListBean.id, userId, true);
                                            } else if (tDeListBean.state == 1) {//失败
                                                //更改状态为3
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userId, 3, true);
                                            } else if (tDeListBean.state == 2) { //异常
                                                App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", userId, -1, true);
                                                errorList.add(tDeListBean.id);
                                            }
                                        }
                                    }

                                    if (errorList.size() == 0) {

                                        List<NoteService.noteSynBean.ListBean> listBeans = bean.list;

                                        for (NoteService.noteSynBean.ListBean listBean : listBeans) {

                                            if (listBean.dataState == 1) {//新增
                                                if (listBean.state == 0) {//成功
                                                    //修改id和状态值
                                                    App.getDBcApplication().updateNoteDetailId(listBean.id, listBean.calendId, userId);
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.calendId, userId, 0, true);
                                                } else if (listBean.state == 1) {//失败  可以不操作,但是避免意外
                                                    //更改状态为1
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userId, 1, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userId, -1, true);
                                                }
                                            } else if (listBean.dataState == 2) {//修改
                                                if (listBean.state == 0) {//成功
                                                    //修改该id状态值
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userId, 0, true);
                                                } else if (listBean.state == 1) {//失败
                                                    //更改状态为2
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userId, 2, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userId, -1, true);
                                                }
                                            } else if (listBean.dataState == 3) {//删除
                                                if (listBean.state == 0) {//成功
                                                    //删除该id的清单
                                                    App.getDBcApplication().deleteNoteTitledetailData(listBean.id, userId, true);
                                                } else if (listBean.state == 1) {//失败
                                                    //更改状态为3
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userId, 3, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, userId, -1, true);
                                                }
                                            }
                                        }
                                        sharedPrefUtil.putString(
                                                getApplication(),
                                                ShareFile.USERFILE,
                                                ShareFile.DOWNREPTIME,
                                                bean.downTime.replace(
                                                        "T", " "));

                                    }
                                    sendNoteOtherCanlender(tuId,title_userid, title, titleid, titleImg, noteusername,sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""),pname);
                                } else {
                                    progressUtil.dismiss();
                                    Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                progressUtil.dismiss();
                                Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

        }
    }

    class SendBena {


        /**
         * delList : null
         * downTime : 2017-07-05T11:03:30
         * list : null
         * message : 成功
         * status : 0
         * tDelList : null
         */

        public Object delList;
        public String downTime;
        public Object list;
        public String message;
        public int status;
        public Object tDelList;

        public Object getDelList() {
            return delList;
        }

        public void setDelList(Object delList) {
            this.delList = delList;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }

        public Object getList() {
            return list;
        }

        public void setList(Object list) {
            this.list = list;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public Object getTDelList() {
            return tDelList;
        }

        public void setTDelList(Object tDelList) {
            this.tDelList = tDelList;
        }
    }


    private void postPersonCalerder(String id,String uname,String titleImg) {

        SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);

        PersonCalerder(0, id, id,
                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0"),
                mySchBean.schDate + " "+mySchBean.schTime+":00",
                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""),
                uname,
                mySchBean.schContent,
                titleImg
        );
    }

    /**
     * 对好友日程进行操作
     *
     * @param type      操作类型  0 添加 1删除  2修改
     * @param cpid
     * @param calendaId
     * @param uid
     * @param time
     * @param name
     * @param nickname
     * @param message
     * @param uPortrait
     */
    private void PersonCalerder(final int type, final String cpid, final String calendaId, final String uid, final String time, final String name, final String nickname, final String message, final String uPortrait) {
        progressUtil.ShowProgress(context, true, true, "日程添加中...");
        final JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            //添加的json
            if (type == 0) {
                jsonObject.put("CAlarmsound", "g_220");
                jsonObject.put("CAlarmsoundDesc", "短提示音");
                jsonObject.put("CLightAppId", 0);
                jsonObject.put("COpenstate", 1);
                jsonObject.put("CPostpone", mySchBean.schIsPostpone);
                jsonObject.put("CRecommendName", name);
                jsonObject.put("CTags", "");
                jsonObject.put("CType", 0);
                jsonObject.put("CTypeDesc", "");
                jsonObject.put("CTypeSpare", "");
                jsonObject.put("calendaId", 0);
                jsonObject.put("cbeforTime", 0);
                jsonObject.put("cdate", time.substring(0, 10));
                jsonObject.put("changTime", time);
                jsonObject.put("cisAlarm", 0);
                jsonObject.put("cpId", cpid);
                jsonObject.put("cretetime", time);
                jsonObject.put("ctime", time.substring(11, 16));

                jsonObject.put("atype", 0);
                jsonObject.put("downNum", 0);
                jsonObject.put("downstate", 0);
                jsonObject.put("endNum", 0);
                jsonObject.put("endState", "0");
                jsonObject.put("id", Integer.valueOf(calendaId));
                jsonObject.put("imgPath", "");
                jsonObject.put("lyNum", 0);
                jsonObject.put("message", message);
                jsonObject.put("parReamrk", "");
                jsonObject.put("pid", "");
                jsonObject.put("poststate", "0");
                jsonObject.put("remark", "");
                jsonObject.put("remark1", android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL);
                jsonObject.put("remark2", "");
                jsonObject.put("remark3", "");
                jsonObject.put("repCalendaState", 0);
                jsonObject.put("repCalendaTime", "");
                jsonObject.put("repColorType", 0);
                jsonObject.put("repDisplayTime", mySchBean.schDisplayTime);
                jsonObject.put("repInStable", 1);
                jsonObject.put("repIsPuase", 0);
                jsonObject.put("repState", 0);
                jsonObject.put("repType", 0);
                jsonObject.put("repTypeParameter", "");
                jsonObject.put("repdatetwo", "");
                jsonObject.put("repinitialcreatedtime", "");
                jsonObject.put("replastcreatedtime", "");
                jsonObject.put("repnextcreatedtime", "");
                jsonObject.put("repstartdate", "");

                jsonObject.put("repstatetwo", 0);
                jsonObject.put("schIsImportant", 0);
                jsonObject.put("status", 1);
                jsonObject.put("uid", Integer.valueOf(uid));
                jsonObject.put("webUrl", "");
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);

        Log.e("TAG", jsonArray.toString());

        StringRequest stringRequest = new StringRequest(Method.POST,URLConstants.HOST+"/appFrends_synFrendCalendaNew.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                FriendsSouSuoActivity.PersonCalerder personCalerder = gson.fromJson(result, FriendsSouSuoActivity.PersonCalerder.class);
                                if (personCalerder.status == 0) {
                                    List<FriendsSouSuoActivity.PersonCalerderListBean> personCalerderListBeanList = personCalerder.list;
                                    if (personCalerderListBeanList.get(0).getState() == 0) {
                                        if (type == 0) {
                                            cpidhandler = cpid;
                                            addItem(cpid, uid, time, personCalerderListBeanList.get(0).calendId + "", name, message, nickname, uPortrait);
                                        }
                                    } else {
                                        progressUtil.dismiss();
                                        Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                                    }
                                }else {
                                    progressUtil.dismiss();
                                    Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                progressUtil.dismiss();
                                Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
                progressUtil.dismiss();
                Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                //添加
                if (type == 0) {
                    map.put("data", "{addData:" + jsonArray.toString() + ",updateData:[],deleData:[]}");
                }
                //删除
                if (type == 1) {
                    map.put("data", "{addData:[],updateData:[] ,deleData:" + jsonArray.toString() + "}");
                }
                //修改
                if (type == 2) {
                    map.put("data", "{addData:[],updateData:" + jsonArray.toString() + ",deleData:[]}");
                }
                return map;
            }
        };
        stringRequest.setTag("synFrendCalendaNew");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    /**
     * 添加日程
     *
     * @param cpid
     * @param uid
     * @param time
     * @param calendId
     * @param name
     * @param message
     * @param nickname
     * @param uPortrait
     */
    private void addItem(String cpid, String uid, String time, String calendId, String name, String message, String nickname, String uPortrait) {
        FriendDownAllScheduleBean friendDownAllScheduleBean = new FriendDownAllScheduleBean();

        friendDownAllScheduleBean.setCAlarmsound("g_220");
        friendDownAllScheduleBean.setCAlarmsoundDesc("短提示音");
        friendDownAllScheduleBean.setCLightAppId("0");
        friendDownAllScheduleBean.setCOpenstate("1");
        friendDownAllScheduleBean.setCPostpone(mySchBean.schIsPostpone);
        friendDownAllScheduleBean.setCRecommendName(name);
        friendDownAllScheduleBean.setCTags("");
        friendDownAllScheduleBean.setCType("0");
        friendDownAllScheduleBean.setCTypeDesc("");
        friendDownAllScheduleBean.setCTypeSpare("");
        friendDownAllScheduleBean.setCalendaId("0");
        friendDownAllScheduleBean.setCbeforTime("0");
        friendDownAllScheduleBean.setCdate(time.substring(0, 10));
        friendDownAllScheduleBean.setChangTime(time);
        friendDownAllScheduleBean.setCisAlarm("0");
        friendDownAllScheduleBean.setCpId(cpid);
        friendDownAllScheduleBean.setCretetime(time);
        friendDownAllScheduleBean.setCtime(time.substring(11, 16));

        friendDownAllScheduleBean.setAtype("0");

        friendDownAllScheduleBean.setDownNum("0");
        friendDownAllScheduleBean.setDownstate("0");

        friendDownAllScheduleBean.setEndNum("0");
        friendDownAllScheduleBean.setEndState("0");

        friendDownAllScheduleBean.setId(calendId);
        friendDownAllScheduleBean.setImgPath("");
        friendDownAllScheduleBean.setLyNum("0");
        friendDownAllScheduleBean.setMessage(message);

        friendDownAllScheduleBean.setParReamrk("");
        friendDownAllScheduleBean.setPoststate("0");
        friendDownAllScheduleBean.setPid("");

        friendDownAllScheduleBean.setRemark("");
        friendDownAllScheduleBean.setRemark1(android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL);
        friendDownAllScheduleBean.setRemark2("");
        friendDownAllScheduleBean.setRemark3("");
        friendDownAllScheduleBean.setRepCalendaState("0");
        friendDownAllScheduleBean.setRepCalendaTime("0");
        friendDownAllScheduleBean.setRepColorType("0");
        friendDownAllScheduleBean.setRepDisplayTime(mySchBean.schDisplayTime);
        friendDownAllScheduleBean.setRepInStable("0");
        friendDownAllScheduleBean.setRepIsPuase("0");
        friendDownAllScheduleBean.setRepState("0");
        friendDownAllScheduleBean.setRepType("0");
        friendDownAllScheduleBean.setRepTypeParameter("");
        friendDownAllScheduleBean.setRepdatetwo("0");
        friendDownAllScheduleBean.setRepinitialcreatedtime("");
        friendDownAllScheduleBean.setReplastcreatedtime("");
        friendDownAllScheduleBean.setRepnextcreatedtime("");
        friendDownAllScheduleBean.setRepstartdate("");
        friendDownAllScheduleBean.setRepState("");

        friendDownAllScheduleBean.setSchIsImportant("0");
        friendDownAllScheduleBean.setStatus("1");

        friendDownAllScheduleBean.setUid(uid);
        friendDownAllScheduleBean.setWebUrl("");


        App.getDBcApplication().insertFriendSchedule(friendDownAllScheduleBean);
        Toast.makeText(context, "发送成功", Toast.LENGTH_SHORT).show();
        progressUtil.dismiss();

        Intent intent = new Intent();
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
    private void AddDailog(final AddFriendsBean friendsbean) {
        final Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
//        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_new_ss_friend, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = getWindowManager().getDefaultDisplay().getWidth();
        dialog.show();
        TextView add = (TextView) more_pop_menu.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean isSave = false;
                List<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> listBeanList = App.getDBcApplication().getAllNewFriendData(userId, false);
                for (NewFriendsActivity.newFriendBean.PageBean.ItemsBean itemsBean : listBeanList) {
                    if (itemsBean.pname.equals(friendsbean.uname)) {
                        isSave = true;
                        Toast.makeText(context, "已存在", Toast.LENGTH_SHORT).show();
                        break;
                    }
                }
                if (!isSave) {
                    newFriendBean.PageBean.ItemsBean itemsBean = new newFriendBean.PageBean.ItemsBean();
                    itemsBean.pname = friendsbean.uname;
                    itemsBean.uid = Integer.valueOf(userId);
                    itemsBean.puid = friendsbean.uid;
                    itemsBean.pimgs = friendsbean.titleImg;
                    itemsBean.id = App.getDBcApplication().getNFMinId() - 1;
                    itemsBean.createTime = DateUtil.nowTime();
                    itemsBean.changeTime = DateUtil.nowTime();
                    itemsBean.remark = "";
                    itemsBean.remark1 = "";
                    itemsBean.type = 0;
                    App.getDBcApplication().saveNewFriendData(itemsBean, 1);
                    Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
                }

                dialog.dismiss();
            }
        });
        TextView cancle_tv = (TextView) more_pop_menu.findViewById(R.id.cancel);
        cancle_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 更新常用联系人信息
     */
    class UpdateUserBean{


        /**
         * status : 0
         * downTime : 2017-07-24T10:40:43
         * message : 成功
         * list : [{"uId":1318823,"uPortrait":"default/pic_9.jpg","uNickName":"游客121318823"}]
         * tDelList : null
         * delList : null
         */

        public int status;
        public String downTime;
        public String message;
        public Object tDelList;
        public Object delList;
        public List<ListBean> list;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public Object getTDelList() {
            return tDelList;
        }

        public void setTDelList(Object tDelList) {
            this.tDelList = tDelList;
        }

        public Object getDelList() {
            return delList;
        }

        public void setDelList(Object delList) {
            this.delList = delList;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public class ListBean {
            /**
             * uId : 1318823
             * uPortrait : default/pic_9.jpg
             * uNickName : 游客121318823
             */

            public int uId;
            public String uPortrait;
            public String uNickName;

            public int getUId() {
                return uId;
            }

            public void setUId(int uId) {
                this.uId = uId;
            }

            public String getUPortrait() {
                return uPortrait;
            }

            public void setUPortrait(String uPortrait) {
                this.uPortrait = uPortrait;
            }

            public String getUNickName() {
                return uNickName;
            }

            public void setUNickName(String uNickName) {
                this.uNickName = uNickName;
            }
        }
    }
}
